package com.chatplus.application.service.file.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chatplus.application.common.constant.GroupCacheNames;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.util.CacheGroupUtils;
import com.chatplus.application.common.util.RedisUtils;
import com.chatplus.application.dao.file.SysOssConfigDao;
import com.chatplus.application.domain.entity.file.SysOssConfigEntity;
import com.chatplus.application.file.constant.OssConstant;
import com.chatplus.application.service.file.SysOssConfigService;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 对象存储配置表业务逻辑实现
 *
 * <p>Table: t_sys_oss_config - 对象存储配置表</p>
 *
 * @author developer
 * @see SysOssConfigEntity
 */
@Service
public class SysOssConfigServiceImpl extends ServiceImpl<SysOssConfigDao, SysOssConfigEntity> implements SysOssConfigService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(SysOssConfigServiceImpl.class);

    private final ObjectMapper objectMapper;

    public SysOssConfigServiceImpl(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 项目启动时，初始化参数到缓存，加载配置类
     */
    @Override
    public void init() {
        List<SysOssConfigEntity> list = list();
        // 加载OSS初始化配置
        for (SysOssConfigEntity config : list) {
            if (config.getStatus().equals(Boolean.FALSE)) {
                continue;
            }
            String configKey = config.getConfigKey();
            if (Boolean.TRUE.equals(config.getDefaultStore())) {
                RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, configKey);
            }
            try {
                CacheGroupUtils.put(GroupCacheNames.SYS_OSS_CONFIG, config.getConfigKey(), objectMapper.writeValueAsString(config));
            } catch (Exception e) {
                LOGGER.message("OSS初始化失败").context("config", config).exception(e).error();
            }
        }
    }

    @Override
    public boolean save(SysOssConfigEntity config) {
        validEntityBeforeSave(config);
        boolean flag = baseMapper.insert(config) > 0;
        if (flag && Boolean.TRUE.equals(config.getStatus())) {
            try {
                CacheGroupUtils.put(GroupCacheNames.SYS_OSS_CONFIG, config.getConfigKey(), objectMapper.writeValueAsString(config));
            } catch (Exception e) {
                LOGGER.message("SysOssConfigServiceImpl init error").context("config", config).exception(e).error();
            }
        }
        return flag;
    }

    @Override
    public boolean updateById(SysOssConfigEntity config) {
        validEntityBeforeSave(config);
        LambdaUpdateWrapper<SysOssConfigEntity> luw = new LambdaUpdateWrapper<>();
        luw.set(ObjectUtil.isNull(config.getPrefix()), SysOssConfigEntity::getPrefix, "");
        luw.set(ObjectUtil.isNull(config.getRegion()), SysOssConfigEntity::getRegion, "");
        luw.set(ObjectUtil.isNull(config.getExt1()), SysOssConfigEntity::getExt1, "");
        luw.set(ObjectUtil.isNull(config.getRemark()), SysOssConfigEntity::getRemark, "");
        luw.eq(SysOssConfigEntity::getId, config.getId());
        boolean flag = baseMapper.update(config, luw) > 0;
        if (flag) {
            try {
                if (Boolean.FALSE.equals(config.getStatus())) {
                    CacheGroupUtils.evict(GroupCacheNames.SYS_OSS_CONFIG, config.getConfigKey());
                }else {
                    CacheGroupUtils.put(GroupCacheNames.SYS_OSS_CONFIG, config.getConfigKey(), objectMapper.writeValueAsString(config));
                }
            } catch (Exception e) {
                LOGGER.message("SysOssConfigServiceImpl init error").context("config", config).exception(e).error();
            }
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysOssConfigEntity entity) {
        if (StringUtils.isNotEmpty(entity.getConfigKey()) && !checkConfigKeyUnique(entity)) {
            throw new BadRequestException("操作配置'" + entity.getConfigKey() + "'失败, 配置key已存在!");
        }
    }

    /**
     * 判断configKey是否唯一
     */
    private boolean checkConfigKeyUnique(SysOssConfigEntity sysOssConfig) {
        long ossConfigId = ObjectUtil.isNull(sysOssConfig.getId()) ? -1L : sysOssConfig.getId();
        SysOssConfigEntity info = baseMapper.selectOne(new LambdaQueryWrapper<SysOssConfigEntity>()
                .select(SysOssConfigEntity::getId, SysOssConfigEntity::getConfigKey)
                .eq(SysOssConfigEntity::getConfigKey, sysOssConfig.getConfigKey()));
        return !ObjectUtil.isNotNull(info) || info.getId() == ossConfigId;
    }

    @Override
    public boolean deleteBatchByIds(Collection<Long> ids) {
        if (CollUtil.containsAny(ids, OssConstant.SYSTEM_DATA_IDS)) {
            throw new BadRequestException("系统内置, 不可删除!");
        }
        List<SysOssConfigEntity> list = CollUtil.newArrayList();
        for (Long configId : ids) {
            SysOssConfigEntity config = baseMapper.selectById(configId);
            list.add(config);
        }
        boolean flag = baseMapper.deleteBatchIds(ids) > 0;
        if (flag) {
            list.forEach(sysOssConfig ->
                    CacheGroupUtils.evict(GroupCacheNames.SYS_OSS_CONFIG, sysOssConfig.getConfigKey()));
        }
        return flag;
    }
}
